First bad version¶
Time: O(LogN); Space: O(1); easy
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example 1:
Input: n = 5
Output: 4
call isBadVersion(3) -> False
call isBadVersion(5) -> True
call isBadVersion(4) -> True
1. Binary Search [O(LogN), O(1)]¶
[15]:
class Solution1(object):
"""
Time: O(LogN)
Space: O(1)
"""
def isBadVersion(self, n):
if n == 4:
return True
else:
return False
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = left + (right - left) // 2
print('call isBadVersion({})'.format(mid), end=' -> ')
if self.isBadVersion(mid):
print('True')
right = mid - 1
else:
print('False')
left = mid + 1
return left
[16]:
s = Solution1()
n = 5
assert s.firstBadVersion(n) == 4
call isBadVersion(3) -> False
call isBadVersion(4) -> True